package net.k3rnel.abugadro;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import net.k3rnel.abugadro.providers.ProjectsDB;
import net.k3rnel.abugadro.providers.Project.Projects;
import net.k3rnel.abugadro.util.NotifyingAsyncQueryHandler;
import net.k3rnel.abugadro.util.UIUtils;
import net.k3rnel.abugadro.util.NotifyingAsyncQueryHandler.AsyncQueryListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class ProjectEditor extends Activity implements AsyncQueryListener{

	public static final String TAG = "Abugadro ProjectEditor";
	private EditText mProjectName;
	private Spinner  mProjectType;
	private EditText mUsername;
	private EditText mPassword;
	private CheckBox mRememberPassword;
	ProgressDialog progressDialog;
	private NotifyingAsyncQueryHandler mHandler;
	private boolean mEditMode = false;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_projects_add);

		final String customTitle = getIntent().getStringExtra(Intent.EXTRA_TITLE);
		((TextView) findViewById(R.id.title_text)).setText(
				customTitle != null ? customTitle : getTitle());

		Spinner typeSpinner = (Spinner) findViewById(R.id.project_types_spinner);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.project_types, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		typeSpinner.setAdapter(adapter);

		progressDialog = new ProgressDialog(this);
		progressDialog.dismiss();

		mProjectName = (EditText) findViewById(R.id.project_name_entry);
		mProjectType = (Spinner) findViewById(R.id.project_types_spinner);
		mUsername = (EditText) findViewById(R.id.project_username_entry);
		mPassword = (EditText) findViewById(R.id.project_password_entry);
		mRememberPassword = (CheckBox) findViewById(R.id.project_check_pass);

		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);

		final String action = getIntent().getAction();
		if (Intent.ACTION_EDIT.equals(action) && savedInstanceState == null) {
			mEditMode = true;
			//			// Start background query to load current state
			final Uri projectUri = getIntent().getData();
			mHandler.startQuery(projectUri, ProjectsQuery.PROJECTION);
			((Button) findViewById(R.id.proj_del)).setText(R.string.option_delete);
			((Button) findViewById(R.id.proj_add)).setText(R.string.option_save);
			((TextView) findViewById(R.id.title_text)).setText(R.string.title_project_edit);
		}

		Button button = (Button) findViewById(R.id.proj_add);
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String projName = mProjectName.getText().toString().toLowerCase();
				String projectType = mProjectType.getSelectedItem().toString();
				int type = 0;
				if(projectType.equals("Launchpad"))
					type = 1;
				//Else, its a GoogleCode project. No need to else. 
				String username = mUsername.getText().toString();
				String password = mPassword.getText().toString();
				boolean rememberPass = mRememberPassword.isChecked();
				if(!projName.equals("")){
					if(rememberPass)
						checkProject(projName,type, username,password);
					else
						checkProject(projName,type, username,"");
				} else createDialog("Wait a minute...","That Project doesn't exist!\nCheck for Typos and double-check the Bug Tracker");
			}
		});
	}

	/** {@inheritDoc} */
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		try {
			if (!cursor.moveToFirst()) return;

			// Load current project content for editing
			mProjectName.setText(cursor.getString(ProjectsQuery.NAME));
			mProjectName.setClickable(false);
			mProjectName.setEnabled(false);
			mProjectName.setFocusable(false);


			mProjectType.setSelection(cursor.getInt(ProjectsQuery.TYPE));
			mProjectType.setFocusable(false);
			mProjectType.setClickable(false);
			mProjectType.setEnabled(false);

			mUsername.setText(cursor.getString(ProjectsQuery.USERNAME));
			String password = cursor.getString(ProjectsQuery.PASSWORD);
			if(password!=null&&!password.equals(""))
				mRememberPassword.setChecked(true);
			mPassword.setText(password);

		} finally {
			if(cursor!=null)
				cursor.close();
		}
	}

	/** Handle "home" title-bar action. */
	public void onHomeClick(View v) {
		UIUtils.goHome(this);
	}
	/** Handle "home" title-bar action. */
	public void onCancelClick(View v) {
		if(!mEditMode)
			UIUtils.goHome(this);
		else{
			showDialog(R.id.dialog_discard_confirm);
		}
	}
	private void deleteProject() {
		if (mEditMode) {
			final Uri projectUri = getIntent().getData();
			mHandler.startDelete(projectUri);

		} 

		finish();
	}
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case R.id.dialog_discard_confirm: {
				return new AlertDialog.Builder(this)
				.setTitle(R.string.title_project_delete)
				.setIcon(android.R.drawable.ic_dialog_alert)
				.setMessage(R.string.project_delete_confirm)
				.setNegativeButton(android.R.string.cancel, null)
				.setPositiveButton(android.R.string.ok, new DiscardConfirmClickListener())
				.setCancelable(false)
				.create();
			}
			case R.id.dialog_progress:{
				progressDialog = new ProgressDialog(ProjectEditor.this);
				progressDialog.setIndeterminate(true);
				progressDialog.setMessage("Loading...");
				progressDialog.setCancelable(false);
				return progressDialog;
			}
		}
		return null;
	}

	private class DiscardConfirmClickListener implements DialogInterface.OnClickListener {
		public void onClick(DialogInterface dialog, int which) {
			deleteProject();
		}
	}
	private void createDialog(String title, String text) {
		AlertDialog ad = new AlertDialog.Builder(this)
		.setPositiveButton("Ok", null)
		.setTitle(title)
		.setMessage(text)
		.create();
		ad.show();
	}

	private void checkProject(final String projectName, final int type,final String username,final String password) {
		Thread t = new Thread() {
			public void run() {
				Looper.prepare();
				try {
					switch(type){
					case 0:
						try{
							if(!ProjectsDB.getInstance().isProjectInDB(getContentResolver(),projectName,type)){
								showDialog(R.id.dialog_progress);
								URL url = new URL("http://code.google.com/feeds/issues/p/"+projectName+"/issues/full/?max-results=1");
								HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
								urlc.setRequestProperty("User-Agent", "Abugadro for Android v"+R.string.version);
								urlc.setRequestProperty("Connection", "close");
								urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
								urlc.connect();
								if (urlc.getResponseCode() == 200) {
									Log.i(TAG,"Project Found");
									ProjectsDB.getInstance().addNewProject(getContentResolver(), projectName, type, username, password);
									progressDialog.dismiss();
									Log.i(TAG,"Project Created");
									finish();
								}else{
									progressDialog.dismiss();
									Log.i(TAG,"Error "+urlc.getResponseCode());
									createDialog("Wait a minute...","That Project doesn't exist, or we don't have access to it.\nError: "+urlc.getResponseCode());
								}
							}else{
								ProjectsDB.getInstance().updateProjectFromTitle(getContentResolver(), projectName, type, username, password);
								finish();
							}
						} catch (MalformedURLException e1) {
							progressDialog.dismiss();
							Log.e(TAG,"MalformedURL",e1);
							createDialog("Urgh.. MalformedURL!","You broke the URL! Project Names don't use slashes, that's probably it.");
						} catch (IOException e) {
							progressDialog.dismiss();
							Log.e(TAG,"IOException",e);
							createDialog("Gah! IOException!","You know what an IOException is, right? \nNo Internet Connectivity. We sorta need that to add a project.");
						}
						break;
					case 1:
						try{
							if(!ProjectsDB.getInstance().isProjectInDB(getContentResolver(),projectName,type)){
								showDialog(R.id.dialog_progress);
								URL url = new URL("http://feeds.launchpad.net/"+projectName+"/latest-bugs.atom"); //Need to find a way to only get one bug or two
								HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
								urlc.setRequestProperty("User-Agent", "Abugadro for Android v"+R.string.version);
								urlc.setRequestProperty("Connection", "close");
								urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
								urlc.connect();
								if (urlc.getResponseCode() == 200) {
									Log.i(TAG,"Project Found");
									ProjectsDB.getInstance().addNewProject(getContentResolver(), projectName, type, username, password);
									Log.i(TAG,"Project Created");
									progressDialog.dismiss();
									finish();
								}else{
									progressDialog.dismiss();
									Log.i(TAG,"Error "+urlc.getResponseCode());
									createDialog("Wait a minute...","That Project doesn't exist, or we don't have access to it.\nError: "+urlc.getResponseCode());
								}
							}else{
								ProjectsDB.getInstance().updateProjectFromTitle(getContentResolver(), projectName, type, username, password);
								finish();	
							}
						} catch (MalformedURLException e1) {
							progressDialog.dismiss();
							Log.e(TAG,"MalformedURL",e1);
							createDialog("Urgh.. MalformedURL!","You broke the URL! Project Names don't use slashes, that's probably it.");
						} catch (IOException e) {
							progressDialog.dismiss();
							Log.e(TAG,"IOException",e);
							createDialog("Gah! IOException!","You know what an IOException is, right? \nNo Internet Connectivity. We sorta need that to add a project.");
						}
						break;
					default:
						finish();
						break;
					}

					//Create Account
				} catch (Exception e) {
					createDialog("What a Terrible Failure", e.getMessage()); //This should never happen. 
				}
				Looper.loop();                
			}
		};
		t.start();
	}
	/** {@link Projects} query parameters. */
	private interface ProjectsQuery {
		String[] PROJECTION = {
				BaseColumns._ID,
				Projects.NAME,
				Projects.TYPE,
				Projects.USERNAME,
				Projects.PASSWORD,
		};
		int NAME = 1;
		int TYPE = 2;
		int USERNAME = 3;
		int PASSWORD = 4;
	}
}